package com.pinusmusic.service.impl;

import com.pinusmusic.dao.MusicDao;
import com.pinusmusic.dao.Music_MusicListDao;
import com.pinusmusic.dao.SingerDao;
import com.pinusmusic.dao.impl.MusicDaoImpl;
import com.pinusmusic.dao.impl.Music_MusicListDaoImpl;
import com.pinusmusic.dao.impl.SingerDaoImpl;
import com.pinusmusic.domain.Music;
import com.pinusmusic.domain.PageBean;
import com.pinusmusic.domain.ResultInfo;
import com.pinusmusic.domain.Singer;
import com.pinusmusic.service.SingerService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

public class SingerServiceImpl implements SingerService {
    private SingerDao singerDao = new SingerDaoImpl();
    private MusicDao musicDao = new MusicDaoImpl();
    private Music_MusicListDao mmDao = new Music_MusicListDaoImpl();

    // 1.创建磁盘文件项工厂
    private DiskFileItemFactory factory = new DiskFileItemFactory();
    // 2.创建文件上传的核心类
    private ServletFileUpload upload = new ServletFileUpload(factory);

    /**
     * 添加歌手
     *
     * @param addSinger
     */
    @Override
    public boolean addSinger(Singer addSinger) {
        return singerDao.addSinger(addSinger);
    }

    @Override
    public void deleteSingerAndMusicBySid(int sid) {
        //查找歌手的歌
        List<Music> music = musicDao.findMusicBySid(sid);
        if (music != null) {
            //查找哪个歌单有这个歌手的歌
            for (int i = 0; i < music.size(); i++) {
                //1.通过歌手的歌id删除歌单中的歌
                mmDao.deleteMusicByMid(music.get(i).getMid());
            }
            musicDao.deleteMusicBySid(sid);
        }
        singerDao.deleteSingerBySid(sid);
    }

    @Override
    public boolean updateSinger(Singer updateSinger) {
        return singerDao.updateSinger(updateSinger);
    }

    @Override
    public Singer findSingerBySid(int sid) {
        return singerDao.findSingerBySid(sid);
    }

    @Override
    public PageBean<Singer> findSingerByPage(int currentPage, int rows, String singerName) {
        PageBean<Singer> pageBean = new PageBean<>();
        //设置总数
        int totalCount = singerDao.getTotalCount(singerName);
        pageBean.setTotalCount(totalCount);
        //设置总页数
        int totalPage = totalCount % rows == 0 ? (totalCount / rows) : (totalCount / rows) + 1;
        pageBean.setTotalPage(totalPage);
        //设置当前页码数 ,设置边界值
        if (currentPage <= 0) currentPage = 1;
        if (currentPage >= totalPage && totalPage > 0) currentPage = totalPage;
        pageBean.setCurrentPage(currentPage);
        //5.设置每页查询的条数
        pageBean.setPageSize(rows);
        int start = (currentPage - 1) * rows;
        List<Singer> singerList = singerDao.findSingerByPage(start, rows, singerName);
        pageBean.setList(singerList);
        return pageBean;
    }

    @Override
    public void deleteSingers(String[] sids) {
        if (sids == null) return;
        for (String sid : sids) deleteSingerAndMusicBySid(Integer.parseInt(sid));
    }

    @Override
    public Singer getAddSinger(HttpServletRequest req) throws IOException {
        //System.out.println("进入了getAddSinger");
        Singer addsinger = new Singer();
        String filepath = "";
        String imgname = "";
        String imgpath = "";

        List<FileItem> list = null;
        try {
            list = upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        for (FileItem item : list) {
            boolean formField = item.isFormField();// 是否是一个普通表单项
            if (formField) {
                // 普通表单项
                String fieldName = item.getFieldName();
                String fieldValue = item.getString("utf-8");
                //System.out.println("上传的是普通表单项" + fieldName + "---" + fieldValue);
                if (fieldName.equals("singername")) {
                    addsinger.setSingername(fieldValue);
                } else if (fieldName.equals("birthday")) {
                    addsinger.setBirthday(fieldValue);
                } else if (fieldName.equals("introduction")) {
                    addsinger.setIntroduction(fieldValue);
                } else {
                    return null;
                }
            } else {
                // 文件上传项
                //共4项   (短)imgname filename imgpath filepath(长)
                imgname = item.getName();
                //zjl.jpg
                //获得的文件名至少为%.%,若长度小于3则无效不写入
                if (imgname==null || imgname.equals("")){
                    addsinger.setSingerimg("images/singerDefault.jpg");
                }else {
                    if (imgname.length() >= 3) {
                        InputStream in = item.getInputStream();
                        String path = req.getServletContext().getRealPath("images");
                        String filename = UUID.randomUUID() + imgname;
                        //f43910b7-b9f8-4f48-affe-79ccefbeeceezjl.jpg
                        //System.out.println("服务器上头像文件名是" + filename);
                        imgname = imgname.substring(0, imgname.lastIndexOf("."));
                        //zjl
                        // System.out.println("要存进数据库的头像名是" + imgname);
                        filepath = path + "\\" + filename;
                        //F:\Java\pinusmusic\src\main\webapp\images\f43910b7-b9f8-4f48-affe-79ccefbeeceezjl.jpg
                        imgpath = filepath.substring(filepath.lastIndexOf("webapp\\") + 7);
                        //images\f43910b7-b9f8-4f48-affe-79ccefbeeceezjl.jpg
                        // System.out.println("要存进数据库的头像文件路径是" + imgpath);
                        // System.out.println("上传头像文件路径是" + filepath);

                        //复制到资源文件夹
                        OutputStream out = new FileOutputStream(filepath);
                        int len = 0;
                        byte[] buffer = new byte[1024];
                        while ((len = in.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }
                        in.close();
                        out.close();
                        addsinger.setSingerimg(imgpath);
                    } else {
                        return null;
                    }
                }
            }
        }
        return addsinger;
    }

    @Override
    public ResultInfo getUpdateSinger(HttpServletRequest req) throws IOException {
        boolean flag = false;//是否成功更新到webapp内
        String errorMsg = "";
        String filepath = "";
        Singer singer = new Singer();
        Singer singer1 = (Singer) req.getSession().getAttribute("singer");
        //System.out.println("sid为" + singer1.getSid());
        singer.setSid(singer1.getSid());
        singer.setSingername(singer1.getSingername());
        // 3.解析request-获得文件项集合
        List<FileItem> list = null;
        try {
            list = upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        for (FileItem item : list) {
            boolean formField = item.isFormField();// 是否是一个普通表单项
            if (formField) {
                // 普通表单项
                String fieldName = item.getFieldName();
                String fieldValue = item.getString("utf-8");
                if (fieldName.equals("birthday")) {
                    singer.setBirthday(fieldValue);
                } else if (fieldName.equals("introduction")) {
                    singer.setIntroduction(fieldValue);
                } else if (fieldName.equals("sid")) {

                } else {
                    errorMsg = "输入了意料之外的键名" + fieldName;
                    break;
                }
                //System.out.println("上传的是普通表单项" + fieldName + "---" + fieldValue);
            } else {
                // 文件上传项
                // 获得上传文件的名称
                String imgName = item.getName();
                //覆潮之下.mp3
                String imgPath = null;
                //获得的文件名至少为%.%,若长度小于3则无效不写入
                if (imgName == null || imgName.equals("")) {
                    flag = true;
                    singer.setSingerimg(singerDao.findPathBySid(singer1.getSid()));
                    errorMsg = "未传入文件，保留原文件";
                    System.out.println(errorMsg);
                } else {
                    if (imgName.length() >= 3) {
                        InputStream in = item.getInputStream();
                        String path = req.getServletContext().getRealPath("images");
                        String filename = UUID.randomUUID() + imgName;
                        //f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
//                    System.out.println("服务器上音乐文件名是"+filename);
                        imgName = imgName.substring(0, imgName.lastIndexOf("."));
                        //覆潮之下
                       //System.out.println("要存进数据库的音乐名是" + imgName);

                        filepath = path + "\\" + filename;
                        //F:\Java\pinusmusic\src\main\webapp\music\f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
                        imgPath = filepath.substring(filepath.lastIndexOf("webapp\\") + 7);
                        //music\f43910b7-b9f8-4f48-affe-79ccefbeecee覆潮之下.mp3
                        //System.out.println("要存进数据库的音乐文件路径是" + imgPath);
//                    System.out.println("上传音乐文件路径是" + filepath);
                        singer.setSingerimg(imgPath);
                        //复制到资源文件夹
                        OutputStream out = new FileOutputStream(filepath);
                        int len = 0;
                        byte[] buffer = new byte[1024];
                        while ((len = in.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }
                        in.close();
                        out.close();
                    } else {
                        errorMsg = "上传的文件名不正确";
                        break;
                    }

                    String delimgpath = singerDao.findPathBySid(singer.getSid());
                    if (delimgpath != null) {
                        File file = new File(delimgpath);
                        file.delete();
                    } else {
                        errorMsg = "原音乐文件路径丢失或无法删除";
                        break;
                    }


                }
                //将音乐文件名和可使用的音乐文件路径写入数据库
                //System.out.println("修改后的歌手：" + singer);
                if (singerDao.updateSinger(singer)) {
                    flag = true;
                } else {
                    errorMsg = "更新数据库记录时发生错误";
                    break;
                }
            }
        }
        //返回json信息
        ResultInfo info = new ResultInfo();
        info.setFlag(flag);
        if (!flag) {
            info.setErrorMsg(errorMsg);
        } else {
            info.setData(filepath);
            info.setErrorMsg("写入成功");
        }
        return info;
    }

    @Override
    public void singerDelete(HttpServletRequest req, HttpServletResponse resp) {
        boolean flag = false;
        String errorMsg = "";
        String sid = req.getParameter("sid");
        String delmusicpath = singerDao.findPathBySid(Integer.parseInt(sid));
        if (delmusicpath != null) {
            File file = new File(delmusicpath);
            file.delete();
        } else {
            errorMsg = "无法查找到目标文件路径";
            System.out.println(errorMsg);
        }
        deleteSingerAndMusicBySid(Integer.parseInt(sid));
    }

    @Override
    public PageBean<Singer> findSingersByName(int currentPage, int rows, String name) {
        PageBean<Singer> pageBean = new PageBean<>();
        //2.获取总记录数
        int totalCount = singerDao.getLikeCount(name);
        pageBean.setTotalCount(totalCount);
        //3.设置总页码数
        int totalPage = totalCount%rows==0?(totalCount/rows):(totalCount/rows)+1;
        pageBean.setTotalPage(totalPage);
        //4.设置当前页码数,设置边界值
        if (currentPage<=0) currentPage=1;
        if (currentPage>=totalPage && totalPage>0) currentPage=totalPage;
        pageBean.setCurrentPage(currentPage);
        //5.设置每页查询的条数
        pageBean.setPageSize(rows);
        //6.设置对应数据
        int start =(currentPage-1)*rows;
        List<Singer> musicList = singerDao.findSingersByName(start, rows, name);
        pageBean.setList(musicList);
        return pageBean;
    }


}
